import 'swiper/css'
import 'swiper/css/bundle'
import './ThemeConfig.scss'

import { useState } from 'react'
import { useMount, useSetState } from 'ahooks'
import { EffectFade } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/react'

import { GetIndexedDB, PutIndexedDB, Encrypt } from './IndexedDB'
import { ThemeBackImageList, UserAvatar, FontFamilyMapping } from '../Config/config'
import { BackGrundTypeConfig, BackGrundType } from './BackGrundType'

import {
    ConfigProvider,
    ColorPicker,
    InputNumber,
    Select,
    Button,
    App,
    Avatar,
    Tag,
    Tooltip,
    Radio,
    Menu,
    Tabs
} from 'antd'
import {
    DesktopOutlined,
    ShakeOutlined,
    QuestionOutlined,
    CustomerServiceOutlined,
    FieldTimeOutlined,
    FundProjectionScreenOutlined,
    LockOutlined,
    LogoutOutlined,
    HomeOutlined,
    MailOutlined
} from '@ant-design/icons'


export const ThemeConfig = ({ PageEvent }) => {
    const NavMapping = [
        { uuid: 1, title: '主题配置', after: '#f83600', before: '#f9d423', Temp: SetThemeConfig },
        { uuid: 2, title: 'Head配置', after: '#00c9ff', before: '#92fe9d', Temp: SetHeadConfig },
        { uuid: 3, title: 'Menu配置', after: '#b721ff', before: '#21d4fd', Temp: SetMenuConfig },
        { uuid: 4, title: 'Body配置', after: '#e8198b', before: '#c7eafd', Temp: SetBodyConfig },
    ]

    const [InitSwiper, setInitSwiper] = useState()
    const [Active, setActive] = useState(1)

    const [Theme, setTheme] = useState()

    useMount(async () => {
        const theme = await GetIndexedDB('theme')
        setTheme(theme)
    })

    const onActive = (uuid) => {
        InitSwiper.slideTo(uuid - 1)
        setActive(uuid)
    }

    if (Theme) {
        return (
            <div className='ThemeConfigItem'>
                <div className='Left'>
                    {NavMapping.map(({ uuid, title }) =>
                        <div
                            key={uuid}
                            onClick={() => onActive(uuid)}
                            className={`Nav ${Active === uuid ? 'active' : ''}`}
                        >
                            {title}
                        </div>
                    )}
                    <div
                        className='indicator'
                        style={{
                            top: (Active - 1) * 48 + 12,
                            background: `linear-gradient(130deg, ${NavMapping[Active - 1].after}, ${NavMapping[Active - 1].before})`
                        }}
                    />
                </div>
                <div className='Right'>
                    <Swiper
                        onSwiper={setInitSwiper}
                        modules={[EffectFade]}
                        noSwiping={true}
                        effect="fade"
                    >
                        {NavMapping.map(({ uuid, Temp }) => (
                            <SwiperSlide key={uuid} className='swiper-no-swiping'>
                                <Temp PageEvent={PageEvent} Theme={Theme} />
                            </SwiperSlide>
                        ))}
                    </Swiper>
                </div>
            </div >
        )
    }

}

const SetThemeConfig = ({ PageEvent, Theme }) => {
    const { message } = App.useApp()
    const [Loading, setLoading] = useState(false)
    const [themeConfig, setThemeConfig] = useState(Theme.themeConfig)
    const ThemeImageMapping = Object.keys(ThemeBackImageList).map(key => ({ value: key, label: key }))
    const BackGrundTypeMapping = Object.keys(BackGrundType).map(key => ({ value: key, label: key }))
    const BackTypeMapping = [{ value: 'Color', label: '纯色' }, { value: 'Image', label: '图片' }, { value: 'Ground', label: '背景墙' }]
    const [DeftultColor, setDeftultColor] = useState(themeConfig.BackType === 'Color' ? themeConfig.BackValue : '#F4F5FA')
    const [DeftultImage, setDeftultImage] = useState(themeConfig.BackType === 'Image' ? themeConfig.BackValue : 'ThemeImageA01')
    const [DeftultGround, setDeftultGround] = useState(themeConfig.BackType === 'Ground' ? themeConfig.BackValue : 'GrundTypeA01')
    const [DeftultData, setDeftultData] = useState(themeConfig.BackType === 'Ground' ? themeConfig.BackData : { color1: '#6CE7DD', color2: '#FAFFB2' })
    const BackGroundSelect = (e) => {
        setDeftultGround(e)
        setDeftultData(BackGrundTypeConfig[e])
    }

    const onSave = async () => {
        setLoading(true)
        const { BackType } = themeConfig
        if (BackType === 'Color') {
            themeConfig.BackValue = DeftultColor
        }
        if (BackType === 'Image') {
            themeConfig.BackValue = DeftultImage
        }
        if (BackType === 'Ground') {
            themeConfig.BackValue = DeftultGround
            themeConfig.BackData = DeftultData
        }
        Theme.themeConfig = themeConfig
        console.log('保存json文件', await Encrypt(Theme))
        PutIndexedDB('theme', Theme)

        setTimeout(() => {
            PageEvent.emit({ type: 'updateTheme' })
            message.success('主题更新成功!')
            setLoading(false)
        }, 500)
    }

    return (
        <div className='SetThemeConfig'>
            <div className='ThemeBox'
                style={themeConfig.BackType === 'Color' ? { background: DeftultColor } :
                    themeConfig.BackType === 'Ground' ? BackGrundType[DeftultGround](DeftultData) : {}
                }
            >
                <div className='BackMask'
                    style={{ background: themeConfig.MaskColor, backdropFilter: `blur(${themeConfig.BackMask}px)` }}
                />
                {themeConfig.BackType === 'Image' && <img className='ImageBack' src={ThemeBackImageList[DeftultImage]} alt="" />}
                <div className='Options'>
                    <div className='Label'>
                        <div>主题色</div>
                        <ColorPicker value={themeConfig.Color} onChangeComplete={e => setThemeConfig({ ...themeConfig, Color: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩颜色</div>
                        <ColorPicker value={themeConfig.MaskColor} onChangeComplete={e => setThemeConfig({ ...themeConfig, MaskColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩比例</div>
                        <InputNumber
                            min={0}
                            value={themeConfig.BackMask}
                            onChange={e => setThemeConfig({ ...themeConfig, BackMask: e })}
                        />
                    </div>
                    <div className='Label'>
                        <div>背景类型</div>
                        <Select
                            value={themeConfig.BackType}
                            options={BackTypeMapping}
                            onChange={e => setThemeConfig({ ...themeConfig, BackType: e })}
                        />
                    </div>
                    {themeConfig.BackType === 'Color' &&
                        <div className='Label'>
                            <div>纯色背景</div>
                            <ColorPicker value={DeftultColor} onChangeComplete={e => setDeftultColor(e.toHexString())} />
                        </div>
                    }
                    {themeConfig.BackType === 'Image' &&
                        <div className='Label'>
                            <div>图片背景</div>
                            <Select
                                value={DeftultImage}
                                options={ThemeImageMapping}
                                onChange={e => setDeftultImage(e)}
                            />
                        </div>
                    }
                    {themeConfig.BackType === 'Ground' &&
                        <div>
                            <div className='Label'>
                                <div>墙类型</div>
                                <Select
                                    value={DeftultGround}
                                    options={BackGrundTypeMapping}
                                    onChange={BackGroundSelect}
                                />
                            </div>
                        </div>
                    }
                </div>

                {themeConfig.BackType === 'Ground' &&
                    <div className='Ground'>
                        {(() => {
                            return Object.keys(DeftultData).map(key => {
                                if (key.includes('color')) {
                                    return (
                                        <div className='Label' key={key}>
                                            <div>{key}</div>
                                            <ColorPicker
                                                value={DeftultData[key]}
                                                onChangeComplete={e => setDeftultData({ ...DeftultData, [key]: e.toHexString() })}
                                            />
                                        </div>
                                    )
                                }
                                if (key.includes('size')) {
                                    return (
                                        <div className='Label' key={key}>
                                            <div>{key}</div>
                                            <InputNumber
                                                value={DeftultData[key]}
                                                onChange={e => setDeftultData({ ...DeftultData, [key]: e })}
                                            />
                                        </div>
                                    )
                                }
                            })
                        })()}
                    </div>
                }
                <div className='SaveButton'>
                    <Button type='primary' onClick={onSave} loading={Loading}>保存主题</Button>
                </div>
            </div>
        </div>
    )
}
const SetHeadConfig = ({ PageEvent, Theme }) => {
    const { message } = App.useApp()
    const NavMapping = [
        { value: 1, label: '切换首页', icon: <DesktopOutlined /> },
        { value: 2, label: '站内通知', icon: <ShakeOutlined /> },
        { value: 3, label: '帮助信息', icon: <QuestionOutlined /> },
        { value: 4, label: '智能客服', icon: <CustomerServiceOutlined /> },
        { value: 5, label: '工作计划', icon: <FieldTimeOutlined /> },
        { value: 6, label: '工作台', icon: <FundProjectionScreenOutlined /> },
        { value: 7, label: '锁屏', icon: <LockOutlined /> },
        { value: 8, label: '退出登录', icon: <LogoutOutlined /> },
    ]

    const [Loading, setLoading] = useState(false)
    const [selectTags, setSelectTags] = useState(Theme.headConfig.optionsList)
    const [AvatarShape, setAvatarShape] = useState(Theme.headConfig.AvatarShape)
    const [AvatarTrigger, setAvatarTrigger] = useState(Theme.headConfig.AvatarTrigger)

    const tagChange = (value, state) => {
        const nextSelectedTags = state ? [...selectTags, value] : selectTags.filter((t) => t !== value)
        setSelectTags(nextSelectedTags)
    }

    const OnSave = async () => {
        setLoading(true)
        const headConfig = {
            optionsList: selectTags,
            AvatarShape: AvatarShape,
            AvatarTrigger: AvatarTrigger
        }
        Theme.headConfig = headConfig
        console.log('保存json文件', await Encrypt(Theme))
        PutIndexedDB('theme', Theme)
        setTimeout(() => {
            PageEvent.emit({ type: 'userInfo' })
            message.success('操作配置成功!')
            setLoading(false)
        }, 500)
    }

    return (
        <div className='SetHeadConfig'>
            <div className='simulation'>
                <div>
                    <div>当前操作项目名称</div>
                    <div>
                        {(() => {
                            return selectTags.map(key => {
                                const Bar = NavMapping.find(v => v.value === key)
                                return (
                                    <Tooltip key={key} title={Bar.label} placement="bottom">
                                        {Bar.icon}
                                    </Tooltip>
                                )
                            })
                        })()}
                    </div>
                </div>
                <Avatar size={48} shape={AvatarShape} src={UserAvatar[Theme.userInfo.Avatar]} />
            </div>
            <div className='options'>
                <div>
                    <div className='Title'>可选操作</div>
                    <div className='FunctionBar'>
                        {NavMapping.map(({ value, label, icon }) =>
                            <Tag.CheckableTag key={value} checked={selectTags.includes(value)} onChange={e => tagChange(value, e)}>
                                {icon} {label}
                            </Tag.CheckableTag>
                        )}
                    </div>
                </div>
                <div>
                    <div className='Title'>用户头像设置</div>
                    <div className='UserAvatar'>
                        <div>
                            <div>头像状态 </div>
                            <Radio.Group value={AvatarShape} onChange={e => setAvatarShape(e.target.value)}>
                                <Radio.Button value="circle">圆形</Radio.Button>
                                <Radio.Button value="square">圆角</Radio.Button>
                            </Radio.Group>
                        </div>
                        <div>
                            <div>触发方式</div>
                            <Radio.Group value={AvatarTrigger} onChange={e => setAvatarTrigger(e.target.value)}>
                                <Radio.Button value="click">点击</Radio.Button>
                                <Radio.Button value="hover">移入</Radio.Button>
                                <Radio.Button value="contextMenu">右键</Radio.Button>
                            </Radio.Group>
                        </div>
                    </div>
                </div>
            </div>
            <div className='OnSave'>
                <Button type='primary' loading={Loading} onClick={OnSave}>保存配置</Button>
            </div>
        </div>
    )
}
const SetMenuConfig = ({ PageEvent, Theme }) => {
    const { message } = App.useApp()
    const boxShadowMapping = [
        { value: '--shadow-none', label: '无阴影' },
        { value: '--shadow-1-down', label: '一级阴影' },
        { value: '--shadow-2-down', label: '二级阴影' },
        { value: '--shadow-3-down', label: '三级阴影' },
    ]

    const [Loading, setLoading] = useState(false)
    const [SelectKey, setSelectKey] = useState('1')
    const [MaskConfig, setMaskConfig] = useSetState(Theme.menuConfig.MaskConfig)
    const [MenuConfig, setMenuConfig] = useSetState(Theme.menuConfig.MenuConfig)

    const items = [
        { key: '1', icon: <HomeOutlined />, label: '首页' },
        {
            key: '2',
            label: '其他菜单',
            icon: <MailOutlined />,
            children: [
                { key: '2-1', label: '菜单一' },
                { key: '2-2', label: '菜单二' },
                { key: '2-3', label: '菜单三' },
                { key: '2-4', label: '菜单亖' },
            ],
        },
    ]

    const onSave = async () => {
        setLoading(true)
        Theme.menuConfig = { MaskConfig, MenuConfig }
        console.log('保存json文件', await Encrypt(Theme))
        PutIndexedDB('theme', Theme)
        setTimeout(() => {
            PageEvent.emit({ type: 'updateMenu' })
            message.success('菜单更新成功!')
            setLoading(false)
        }, 500)
    }

    return (
        <div className='SetMenuConfig'>
            <div className='MenuLook'
                style={{
                    '--itemColor': MenuConfig.itemColor,
                    '--itemSelectedColor': MenuConfig.itemSelectedColor,
                    '--itemActiveBg': MenuConfig.itemActiveBg,
                    '--itemSelectedBg': MenuConfig.itemSelectedBg,
                    '--fontSize': MenuConfig.fontSize,
                    '--fontFamily': MenuConfig.fontFamily,
                    '--iconSize': MenuConfig.iconSize,
                    '--iconMarginInlineEnd': MenuConfig.iconMarginInlineEnd,
                    '--itemBorderRadius': MenuConfig.itemBorderRadius,
                    '--itemHeight': MenuConfig.itemHeight,
                }}
            >
                <div className="Mask"
                    style={{
                        background: MaskConfig.back,
                        backdropFilter: `blur(${MaskConfig.blur}px)`,
                        borderRadius: MaskConfig.radio,
                        boxShadow: `var(${MaskConfig.shoadow})`
                    }}
                />
                <Menu
                    selectedKeys={[SelectKey]}
                    defaultOpenKeys={['2']}
                    mode="inline"
                    items={items}
                    onSelect={({ key }) => setSelectKey(key)}
                />
            </div>
            <div className='Options'>
                <div className='Title'>遮罩设置</div>
                <div className='FormItem'>
                    <div className='Label'>
                        <div>遮罩颜色</div>
                        <ColorPicker value={MaskConfig.back} onChangeComplete={e => setMaskConfig({ back: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩比例</div>
                        <InputNumber min={0} value={MaskConfig.blur} onChange={e => setMaskConfig({ blur: e })} />
                    </div>
                    <div className='Label'>
                        <div>边框阴影</div>
                        <Select options={boxShadowMapping} value={MaskConfig.shoadow} onChange={e => setMaskConfig({ shoadow: e })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩圆角</div>
                        <InputNumber min={0} value={MaskConfig.radio} onChange={e => setMaskConfig({ radio: e })} />
                    </div>
                </div>
                <div className='Title'>菜单设置</div>
                <div className='FormItem'>
                    <div className='Label'>
                        <div>默认颜色</div>
                        <ColorPicker value={MenuConfig.itemColor} onChangeComplete={e => setMenuConfig({ itemColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>选中颜色</div>
                        <ColorPicker value={MenuConfig.itemSelectedColor} onChangeComplete={e => setMenuConfig({ itemSelectedColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>选中背景</div>
                        <ColorPicker value={MenuConfig.itemActiveBg} onChangeComplete={e => setMenuConfig({ itemActiveBg: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>激活背景</div>
                        <ColorPicker value={MenuConfig.itemSelectedBg} onChangeComplete={e => setMenuConfig({ itemSelectedBg: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>菜单字号</div>
                        <InputNumber min={0} value={MenuConfig.fontSize} onChange={e => setMenuConfig({ fontSize: e })} />
                    </div>
                    <div className='Label'>
                        <div>菜单字体</div>
                        <Select
                            options={FontFamilyMapping}
                            value={MenuConfig.fontFamily}
                            onChange={e => setMenuConfig({ fontFamily: e })}
                        />
                    </div>
                    <div className='Label'>
                        <div>图标大小</div>
                        <InputNumber min={0} value={MenuConfig.iconSize} onChange={e => setMenuConfig({ iconSize: e })} />
                    </div>
                    <div className='Label'>
                        <div>图标距离</div>
                        <InputNumber min={0} value={MenuConfig.iconMarginInlineEnd} onChange={e => setMenuConfig({ iconMarginInlineEnd: e })} />
                    </div>
                    <div className='Label'>
                        <div>背景圆角</div>
                        <InputNumber min={0} value={MenuConfig.itemBorderRadius} onChange={e => setMenuConfig({ itemBorderRadius: e })} />
                    </div>
                    <div className='Label'>
                        <div>背景行高</div>
                        <InputNumber min={0} value={MenuConfig.itemHeight} onChange={e => setMenuConfig({ itemHeight: e })} />
                    </div>
                </div>

                <div className='OnSave'>
                    <Button type='primary' loading={Loading} onClick={onSave}>保存菜单</Button>
                </div>
            </div>
        </div>
    )
}
const SetBodyConfig = ({ PageEvent, Theme }) => {
    const { message } = App.useApp()
    const [Loading, setLoading] = useState(false)
    const [NavConfig, setNavConfig] = useSetState(Theme.bodyConfig.NavConfig)
    const [BoxConfig, setBoxConfig] = useSetState(Theme.bodyConfig.BoxConfig)

    const onSave = async () => {
        setLoading(true)
        Theme.bodyConfig = { NavConfig, BoxConfig }
        console.log('保存json文件', await Encrypt(Theme))
        PutIndexedDB('theme', Theme)
        setTimeout(() => {
            PageEvent.emit({ type: 'updateBody' })
            message.success('菜单更新成功!')
            setLoading(false)
        }, 500)
    }

    return (
        <div className='SetBodyConfig'>
            <div className='BodyLook' style={{
                '--background': BoxConfig.background,
                '--backdropFilter': BoxConfig.backdropFilter,
                '--padding': BoxConfig.padding,
                '--borderRadius': BoxConfig.borderRadius
            }}>
                <ConfigProvider theme={{ components: { Tabs: NavConfig } }}>
                    <Tabs type="card" items={new Array(3).fill(null).map((_, i) => ({ label: `标签 ${i + 1}`, key: i, children: `标签内容 ` }))} />
                </ConfigProvider>
            </div>
            <div className='Options'>
                <div className='Title'>导航设置</div>
                <div className="FormItem">
                    <div className='Label'>
                        <div>默认背景色</div>
                        <ColorPicker value={NavConfig.cardBg} onChangeComplete={e => setNavConfig({ cardBg: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>默认文字颜色</div>
                        <ColorPicker value={NavConfig.itemColor} onChangeComplete={e => setNavConfig({ itemColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>选中文字颜色</div>
                        <ColorPicker value={NavConfig.itemHoverColor} onChangeComplete={e => setNavConfig({ itemHoverColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>激活文字颜色</div>
                        <ColorPicker value={NavConfig.itemSelectedColor} onChangeComplete={e => setNavConfig({ itemSelectedColor: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>边框演示</div>
                        <Select
                            options={[{ value: 'solid', label: '实线' }, { value: 'dashed', label: '虚线' }]}
                            value={NavConfig.lineType}
                            onChange={e => setNavConfig({ lineType: e })}
                        />
                    </div>
                    <div className='Label'>
                        <div>标签间距</div>
                        <InputNumber min={0} value={NavConfig.cardGutter} onChange={e => setNavConfig({ cardGutter: e })} />
                    </div>
                </div>
                <div className='Title'>主体设置</div>
                <div className="FormItem">
                    <div className='Label'>
                        <div>遮罩颜色</div>
                        <ColorPicker value={BoxConfig.background} onChangeComplete={e => setBoxConfig({ background: e.toHexString() })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩比例</div>
                        <InputNumber min={0} value={BoxConfig.backdropFilter} onChange={e => setBoxConfig({ backdropFilter: e })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩内距</div>
                        <InputNumber min={0} value={BoxConfig.padding} onChange={e => setBoxConfig({ padding: e })} />
                    </div>
                    <div className='Label'>
                        <div>遮罩圆角</div>
                        <InputNumber min={0} value={BoxConfig.borderRadius} onChange={e => setBoxConfig({ borderRadius: e })} />
                    </div>
                </div>

                <div className='OnSave'>
                    <Button type='primary' loading={Loading} onClick={onSave}>保存菜单</Button>
                </div>
            </div>
        </div>
    )
}